<?php
namespace Demo\Controller;

use Common\Controller\ControllerBaseWeixin;
use Common\Model\UserModel as User;
use Common\Model\ConfigModel as Config;

/**
 * 微信公众平台开发者模式接口
 * @author codebean
 *
 */
class InterfaceController extends ControllerBaseWeixin
{

    /**
     * [subscribe 订阅]
     *
     * @return [type] [description]
     */
    public function subscribe($obj)
    {
        parent::subscribe($obj);
        
        $this->welcome($obj);
    }

    /**
     * [answer 普通文本事件]
     *
     * @return [type] [description]
     */
    public function answer($obj)
    {
        $keyword = $this->keyword;
        if( $keyword=='mp' ){
            $this->qr($obj);
        }else{
            $this->default_answer($obj);
        }
    }

    /**
     * [clickEvent 自定义菜单点击事件]
     *
     * @param [type] $obj
     *            [description]
     * @return [type] [description]
     */
    public function clickEvent($obj)
    {
        $key = $obj->EventKey;
        switch ($key) {
            case "mp":
                $this->qr($obj);
                break;
            default:
                break;
        }
    }

    /**
     * 扫描事件
     * @param unknown $obj            
     */
    public function ScanEvent($obj)
    {
        
        $code = (string)$obj->EventKey;
        
        if( $this->userInfo && $this->userInfo['flag']==0 ){
            $u = new User();
            $u->addFans($code, $this->uid , 4 );
        }
        
        echo "";
        die();
    }

    /**
     * [viewEvent 自定义菜单URL事件]
     *
     * @param [type] $obj
     *            [description]
     * @return [type] [description]
     */
    public function viewEvent($obj)
    {
        $key = $obj->EventKey;
        echo "";
        die();
    }

    /**
     * 新关注欢迎图文
     */
    private function welcome($obj)
    {
        $config = new Config();
        $welcome = $config->getConfig("WELCOME_TXT");
        
        if ($welcome)
        {
            $order = array(
                "\r\n",
                " ",
                "\n",
                "\r",
                "\t"
            );
            $welcome_tmp = str_replace($order, '', $welcome);
            $data = json_decode($welcome_tmp, true);
        }
        
        if (is_array($data))
        {
            $this->sendPicMsg($data);
        } else if ($welcome)
        {
            $this->sendTextMsg($welcome);
        } else
        {
            echo "";
        }
    }

    /**
     * 默认回复
     */
    private function default_answer($obj)
    {
        $config = new Config();
        $welcome = $config->getConfig("DEFAULT_REPLY_TXT");
    
        if ($welcome)
        {
            $order = array(
                "\r\n",
                " ",
                "\n",
                "\r",
                "\t"
            );
            $welcome_tmp = str_replace($order, '', $welcome);
            $data = json_decode($welcome_tmp, true);
        }
    
        if (is_array($data))
        {
            $this->sendPicMsg($data);
        } else if ($welcome)
        {
            $this->sendTextMsg($welcome);
        } else
        {
            echo "";
        }
    }
    

    /**
     * 生成带渠道的二维码
     * @param unknown $obj
     */
    private function qr($obj)
    {
        $userInfo = $this->userInfo;
    
        $config = new Config();
    
        $open_obj = new OpenId();
        $where = array();
        $where['uid'] = $this->uid;
        $where['wxhao'] = C('WX_HAO');
    
        $open_info = $open_obj->where($where)->find();
    
        $media_id = $open_info['media_id'] ? $open_info['media_id'] : false;
    
        //是否永久
        $media_limit = $open_info['media_limit']==1 ? true : false;
    
        //media id是否失效
        $media_is_expire = ((time() - $open_info['media_time']) > 3600 * 24 * 3) ? true : false;
    
        //二维码是否失效
        $media_limit_is_expire = ((time() - $open_info['media_time']) > 3600 * 24 * 30) ? true : false;
    
        $media_path = $open_info['media_path'];
    
        if ( empty($media_id) && empty($media_path) ||( !$media_limit && $media_limit_is_expire )  )
        {
            $u_qr = D('qr');
            $add = array();
            $add['userid'] = $userInfo['id'];
            $add['state'] = 1;
            $add['wxhao'] = C('WX_HAO');
            $u_qr->add($add);
    
            $this->sendTextMsg('您的专属二维码正在生成中，请耐心等待1-2分钟...');
            return false;
        }
        else if ($media_path && $media_is_expire )
        {
            $domain = C('CDN_DOMAIN');
    
            $txt = <<<EOT
<a href="http://{$domain}{$media_path}">点击此次查看你的二维码</a>
    
长按图片，保存到手机。记得发给你的小伙伴啊！
EOT;
            $this->sendTextMsg($txt);
            return false;
        }
    
        $this->sendImage($media_id);
    }   
    
    
    /**
     * 生成登录的URL，并跳转到$url
     * @param unknown $url
     */
    private function encodeUrl( $url )
    {
        $dd = array();
        $dd[] = $timestamp = time();
        $dd[] = $uid = $this->uid;
        $dd[] = $url;
    
        $dd = base64_encode(implode('~~~', $dd));
    
        $tickt = md5(C('URL_ENCODE_KEY') . $timestamp . $uid);
    
        $url = U("Auth/check@".C("MAIN_DOMAIN"), array(
            "data" => $dd,
            'tickt' => $tickt,
        ), true, true);
    
        return $url;
    }
}